package com.keke.servlet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.keke.pojo.Role;
import com.keke.pojo.User;
import com.keke.service.role.RoleService;
import com.keke.service.role.RoleServiceImpl;
import com.keke.service.user.UserService;
import com.keke.service.user.UserServiceImpl;
import com.keke.util.Constants;
import com.keke.util.PageSupport;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.sun.org.apache.bcel.internal.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//实现Servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("savepwd".equals(method) && method != null) {
            this.updatePwd(req, resp);
        }else if("pwdmodify".equals(method) && method != null){
            this.pwdModify(req, resp);
        }else if("query".equals(method) && method != null ){
            this.query(req, resp);
        }else if("deluser".equals(method) && method!=null){
            this.delUser(req,resp);
        }else if("modify".equals(method)&& method!=null){
            this.getUserById(req,resp,"usermodify.jsp");
        }else if("view".equals(method)&& method!=null){
            this.getUserById(req,resp,"userview.jsp");
        }else if("modifyexe".equals(method)&&method!=null){
            this.modify(req,resp);
        }else if("add".equals(method)&&method!=null){
            this.add(req,resp);
        }else if("getrolelist".equals(method)&&method!=null){
            this.getRoleList(req,resp);
        }else if("ucexist".equals(method)&&method!=null){
            this.userCodeExist(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session里面拿id
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String newPassword = req.getParameter("newpassword");

        System.out.println("newPassword:"+newPassword);
        boolean flag=false;

        if(attribute!=null && newPassword!=null){
            UserService userService=new UserServiceImpl();
            flag = userService.updatePwd(((User) attribute).getId(), newPassword);
            if(flag){
                req.setAttribute("message","修改密码成功！");
                //密码修改成功，移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败！");
            }
        }else{
            req.setAttribute("message","新密码设置有问题");
        }
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
    }

    //验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Map<String, String> resultMap = new HashMap<String, String>();
        String oldpassword = req.getParameter("oldpassword");
        // 旧密码输入为空
        if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "error");
        } else {
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            // 当前用户session过期，请重新登录
            if (o == null) {
                resultMap.put("result", "sessionerror");
            } else {
                String password = ((User) o).getUserPassword();
                System.out.println(("原密码" + ((User) o).getUserPassword()) + "输入的密码" + oldpassword);
                // 旧密码正确
                if (oldpassword.equals(password)) {
                    resultMap.put("result", "true");
                    // 旧密码输入不正确
                } else {
                    resultMap.put("result", "false");
                }
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //重点、难点
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole=0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;
        //第一个走这个请求一定是第一页，页面大小固定
        int pageSize = 5;   //写到配置文件中，方便后期修改
        int currentPageNo=1;

        if(queryUserName==null){
            queryUserName="";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole=Integer.parseInt(temp);   //给查询赋值
        }
        if(pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户总总数   分页：上一页、下一页
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = totalCount/pageSize + 1;
        //控制首页和尾页
        //如果页面要小于1了，就显示第一页的东西
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }
        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //增加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("进入到addUser函数");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyBy(user.getCreatedBy());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }


    }

    //删除用户
    public void delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("uid");
        Integer delId=0;

        try {
            delId=Integer.parseInt(id);
        } catch (NumberFormatException e) {
            delId=0;
        }
        HashMap<String,String> resultMap= new HashMap<String, String>();
        if(delId<=0){
            resultMap.put("delResult","notexist");
        }else{
            UserService userService=new UserServiceImpl();
            if(userService.deleteUserById(delId)){
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    //修改用户
    public void getUserById(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
        String id = req.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            req.setAttribute("user",user);
            req.getRequestDispatcher(url).forward(req,resp);
        }
    }

    //得到角色
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(roleList));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改用户
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        int id = Integer.valueOf(req.getParameter("uid"));

        System.out.println("user code =="+userCode);

        User user = new User();
        user.setId(id);
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        userService.modify(user);
        resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
    }

    //获取用户编码是否存在
    private void userCodeExist(HttpServletRequest req, HttpServletResponse resp)  {
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserByUserCode(req.getParameter("userCode"));
        Map<String, String> resultMap = new HashMap<String, String>();
        if (user.getUserCode() == null) {
            resultMap.put("userCode", "notExist");
        } else {
            resultMap.put("userCode", "exist");
        }
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSON.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

}
